package com.srwl.mytx.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.AliService;
import com.srwl.mytx.service.CouponService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.R;
import com.srwl.mytx.utils.Utils;
import com.srwl.redpacketui.callback.GreetingTextWatcher;
import com.srwl.redpacketui.ui.fragment.SendPacketBaseFragment;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SendSinglePacketFragment extends SendPacketBaseFragment {
    static String TAG = SendSinglePacketFragment.class.getSimpleName();
    private OnFragmentInteractionListener interactionListener;
    private EditText mEtMoneyAmount;

    private EditText mEtGreeting;

    private TextView mTvMoneyAmount;

    private Button mBtnPutMoney;

    private String mMoneyAmount;

    private TextView mTvAmount;

    private TextView mTvMoneyUnit;
    private String greeting;

    public static SendSinglePacketFragment newInstance(String targetId) {
        SendSinglePacketFragment fragment = new SendSinglePacketFragment();
        Bundle args = new Bundle();
        args.putString("targetId", targetId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.rp_fragment_single_chat_packet;
    }


//    @Override
//    protected View getLoadingTargetView(View view) {
//        return view.findViewById(R.id.target_layout);
//    }


    @Override
    protected void initViewsAndEvents(View view, Bundle savedInstanceState) {
        super.initViewsAndEvents(view, savedInstanceState);
        mEtGreeting = view.findViewById(R.id.et_greetings);
        mEtGreeting.setHint(mGreetingArray[0]);
        mBtnPutMoney = view.findViewById(R.id.btn_single_put_money);
        mBtnPutMoney.setOnClickListener(this);
        final View changeGreeting = view.findViewById(R.id.btn_layout);
        changeGreeting.setOnClickListener(this);
        enableButton(false);
        mTvAmount = (TextView) view.findViewById(R.id.tv_money_amount);
        mTvMoneyUnit = (TextView) view.findViewById(R.id.tv_money_unit);
        mEtMoneyAmount = (EditText) view.findViewById(R.id.et_money_amount);
        mTvMoneyAmount = (TextView) view.findViewById(R.id.tv_money);
        mPopupParent = getActivity().findViewById(R.id.title_bar);
        initPopupWindow();
        mEtGreeting.addTextChangedListener(new GreetingTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
            }
        });
        mTvMoneyAmount.setText(getString(R.string.rp_str_amount_zero));
        mEtMoneyAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    String moneyAmount = mEtMoneyAmount.getText().toString();
                    if (!TextUtils.isEmpty(moneyAmount)) {
                        if (moneyAmount.length() == 1 && moneyAmount.indexOf(".") == 0) {
                            enableButton(false);
                            setAmountRedColor();
                            showPopupWindow(mPopupParent, mTvPopupMsg, getString(R.string.input_money_error));
                        } else {
                            try {
                                double money = Double.valueOf(moneyAmount);
                                if (money == 0) {
                                    enableButton(false);
                                    setAmountRedColor();
                                    showPopupWindow(mPopupParent, mTvPopupMsg, getString(R.string.input_money_error));
                                }
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
        mEtMoneyAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // updateLimit();
                mEtMoneyAmount.setTextColor(ContextCompat.getColor(mContext, R.color.rp_text_black));
                mTvAmount.setTextColor(ContextCompat.getColor(mContext, R.color.rp_text_black));
                mTvMoneyUnit.setTextColor(ContextCompat.getColor(mContext, R.color.rp_text_black));
                mTvMoneyAmount.setTextColor(ContextCompat.getColor(mContext, R.color.rp_text_black));
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    mTvMoneyAmount.setText(getString(R.string.rp_str_amount_zero));
                    enableButton(false);
                    hidePopupWindow();
                } else if (s.length() == 1 && s.toString().indexOf(".") == 0) {
                    enableButton(false);
                    hidePopupWindow();
                } else {
                    double money;
                    try {
                        money = Double.valueOf(s.toString());
                        int posDot = s.toString().indexOf(".");
                        if (money == 0) {
                            //当用户输入.00时,提示输入金额错误
                            if (posDot >= 0 && s.length() > 2) {
                                String[] st = s.toString().split("\\.");
                                if (st.length == 2 && st[1].equals("00")) {
                                    mTvMoneyAmount.setText(getString(R.string.rp_str_amount_zero));
                                    mTvMoneyAmount.setTextColor(ContextCompat.getColor(mContext, R.color.rp_text_black));
                                    enableButton(false);
                                    setAmountRedColor();
                                    showPopupWindow(mPopupParent, mTvPopupMsg, mContext.getString(R.string.input_money_error));
                                } else {
                                    hidePopupWindow();
                                    mTvMoneyAmount.setText(getString(R.string.rp_str_amount_zero));
                                    enableButton(false);
                                }
                            } else {
                                hidePopupWindow();
                                if (getStartZeroNumber(s.toString()) < 9) {
                                    mTvMoneyAmount.setText(getString(R.string.rp_str_amount_zero));
                                    enableButton(false);
                                }
                            }
                            return;
                        }
                        if (posDot < 0) {//只有在没有小数点的情况下走下面方法
                            if (s.toString().startsWith("0") && money >= 1) {
                                if (getStartZeroNumber(s.toString()) == 9) {
                                    return;
                                }
                            }
                        }
                        if (money < mMinLimit) {
                            enableButton(false);
                            setAmountRedColor();
                            mTvMoneyAmount.setTextColor(ContextCompat.getColor(mContext, R.color.rp_money_red_light));
                            String minLimit = String.format(getString(R.string.input_money_limited_minimum), getNumberLimit(mMinLimit));
                            showPopupWindow(mPopupParent, mTvPopupMsg, minLimit);
                            return;
                        }
                        if (money > mSingleLimit) {
                            enableButton(false);
                            setAmountRedColor();
                            mTvMoneyAmount.setText(String.format("￥%s", Utils.moneyFormat(money)));
                            String limit = String.format(mContext.getString(R.string.input_money_limited_max), getNumberLimit(mSingleLimit));
                            showPopupWindow(mPopupParent, mTvPopupMsg, limit);
                            return;
                        }
                        enableButton(true);
                        mTvMoneyAmount.setText(String.format("￥%s", Utils.moneyFormat(money)));
                        hidePopupWindow();
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                int posDot = temp.indexOf(".");
                if (posDot < 0) {
                    if (temp.length() - 1 > 8) {
                        s.delete(9, 10);
                    }
                    return;
                }
                if (temp.length() - posDot - 1 > 2) {
                    s.delete(posDot + 3, posDot + 4);
                }
            }
        });
    }

    private void setAmountRedColor() {
        enableButton(false);
        mEtMoneyAmount.setTextColor(ContextCompat.getColor(mContext, R.color.rp_money_red_light));
        mTvAmount.setTextColor(ContextCompat.getColor(mContext, R.color.rp_money_red_light));
        mTvMoneyUnit.setTextColor(ContextCompat.getColor(mContext, R.color.rp_money_red_light));
    }

    private void enableButton(boolean enable) {
        mBtnPutMoney.setEnabled(enable);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);//必须调用父类方法
        if (v.getId() == R.id.btn_single_put_money) {
            if (ClickUtil.isFastClick()) return;
            hideSoftKeyboard();
            mMoneyAmount = mEtMoneyAmount.getText().toString().trim();
            greeting = mEtGreeting.getText().toString().trim();
            if (verifyParams()) return;
            if (TextUtils.isEmpty(greeting)) {
                greeting = mEtGreeting.getHint().toString();
            }
            final Coupon coupon = new Coupon();
            coupon.setAmount(Double.valueOf(mMoneyAmount));
            coupon.setuId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
            coupon.settId(targetId);
            //sendAliFundCoupon(coupon, body);
            //发送金币红包
            coupon.setType(Constant.COUPON_TYPE_SINGLE);
            //coupon.setCreated(new Date());

            preparePay(coupon);


        }
        if (v.getId() == R.id.btn_layout) {
            String greeting;
            if (mArrayIndex < mGreetingArray.length) {
                greeting = mGreetingArray[mArrayIndex];
                mArrayIndex++;
            } else {
                mArrayIndex = 0;
                greeting = mGreetingArray[mArrayIndex];
                mArrayIndex++;
            }
            mEtGreeting.setText(greeting);
        }
    }

    /**
     * 准备支付
     *
     * @param coupon
     */
    private void preparePay(final Coupon coupon) {

        new PayUtils(coupon.getAmount(), getActivity(), payPassword -> sendCoinCoupon(coupon, payPassword));

    }

    /**
     * 发送金币红包
     *
     * @param coupon
     */
    private void sendCoinCoupon(Coupon coupon, String payPassword) {
        showLoading();

        Map<String, Object> body = new HashMap<>();
        if (!TextUtils.isEmpty(payPassword)) {
            body.put("payPassword", payPassword);
        }
        body.put("coupon", coupon);
        RetrofitManager.getInstance().createRequest(CouponService.class)
                .sendSingleCoupon(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        hideLoading();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "发金币红包出错：" + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "发金币红包出错：" + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(getString(R.string.balance_not_enough));
                                    break;
                                case Constant.GET_LOCK_FAIL:
                                case Constant.FUND_COUPON_EOOR:
                                    showToast(getString(R.string.system_busy));
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        Log.d(TAG, "发金币红包完成");
                        JSONObject data = (JSONObject) result.getData();
                        double totalBalance = data.getDouble("balance");
                        Date expiryDate = data.getDate("expiryDate");
                        //更新本地余额
                        UserProfileManager.getInstance().setUserBalance(totalBalance);
                        //补齐红包id,因为在接收红包的时候，会用到id
                        String couponId = data.getString("couponId");
                        coupon.setId(couponId);
                        //补齐过期时间
                        coupon.setExpiryDate(expiryDate);

                        if (interactionListener != null) {
                            coupon.setGreeting(greeting);
                            coupon.setStatus(Constant.COUPON_STATUS_RECEIVABLE);
                            interactionListener.onPayFundCouponSuccess(coupon);
                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        hideLoading();
                        Log.e(TAG, "发红包出错：" + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });
    }


    /**
     * 发送阿里现金红包
     *
     * @param coupon
     * @param body
     */
    private void sendAliFundCoupon(final Coupon coupon, JSONObject body) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(mContext, mContext.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        showLoading();
        RetrofitManager.getInstance().createRequest(AliService.class)
                .getCouponUrl(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        hideLoading();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {

                            Log.e(TAG, "发红包请求链接出错：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "发红包请求链接出错：" + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.TOKEN_INVALID:


                                    break;


                            }

                            return;
                        }
                        //  String fundCouponUrl = (String) result.getData();
                        // Log.d(TAG,"发红包请求链接完成："+fundCouponUrl);
                        String outOrderId = (String) result.getData();
                        // TODO: 2018/9/2 调用支付宝sdk,发起支付，等支付宝认证通过了才能测试了，沙箱环境貌似没法测试 红包无线支付

                        //假设已经在支付宝app 支付成功了，现在去服务端验证签名
                        //因为现在是测试，返回的是发送红包的ID,
                        coupon.setId(outOrderId);
                        validateSign(outOrderId, coupon);


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        hideLoading();
                        Log.e(TAG, "发红包出错：" + t.getMessage());
                    }
                });
    }

    private void validateSign(String outOrderId, final Coupon coupon) {

        RetrofitManager.getInstance().createRequest(AliService.class)
                .aliCouponValidateSign(outOrderId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {

                            Log.e(TAG, "发红包同步验证出错：" + response.message());
                            return;
                        }


                        if (result.isError()) {
                            Log.e(TAG, "发红包同步验证出错：" + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.FUND_COUPON_EOOR:

                                    showToast("红包支付验证出错，如果扣款，24小时内会退回");
                                    return;

                            }
                        }
                        Log.i(TAG, "发红包同步验证完成：" + result.getMsg());
                        if (interactionListener != null) {
                            coupon.setGreeting(greeting);
                            interactionListener.onPayFundCouponSuccess(coupon);
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "发红包同步验证出错：" + t.getMessage());
                    }
                });


    }

    private boolean verifyParams() {
        if (TextUtils.isEmpty(mMoneyAmount)) {
            showPopupWindow(mPopupParent, mTvPopupMsg, mContext.getString(R.string.input_money_amount));
            return true;
        }
        if (Double.valueOf(mMoneyAmount) <= 0) {
            showPopupWindow(mPopupParent, mTvPopupMsg, mContext.getString(R.string.input_money_error));
            return true;
        }
        if (Double.valueOf(mMoneyAmount) > mSingleLimit) {
            String limit = String.format(mContext.getResources().getString(R.string.input_money_limited_max), getNumberLimit(mSingleLimit));
            showPopupWindow(mPopupParent, mTvPopupMsg, limit);
            return true;
        }
        return false;
    }

    public void setInteractionListener(OnFragmentInteractionListener interactionListener) {
        this.interactionListener = interactionListener;
    }

    public interface OnFragmentInteractionListener {

        void onPayFundCouponSuccess(Coupon coupon);

        void showToast(String message);
    }


}
